import net from 'net';

let _conn;
let receivers;
let receiverBuffer;
let readIndex;
let chainPackage;

let setChainPackage = (tid, buffer) => {
    if (chainPackage[tid] === null) {
        chainPackage[tid] = [];
    }
    chainPackage[tid].push(buffer);
};

let cleanChainPackage = (tid) => {
    if (chainPackage[tid]) {
        chainPackage[tid] = [];
    }
};

let getChainPackage = (tid) => {
    return chainPackage[tid];
};


/**
 * 分析报文
 * @return {[type]} [description]
 */
let analysisBuffer = () => {
    if (receiverBuffer && receiverBuffer.length > 3) {
        let totalBuffer;
        //如果 CRP 层设置过压缩算法,则压缩后的 FTDC 层的长度计算方法为 XMP 层的长度字段 (xmp.Length)减去 CRP 层的长度。
        if (readIndex > 0) {
            totalBuffer = receiverBuffer.slice(readIndex);
        } else {
            totalBuffer = receiverBuffer;
        }

        if (totalBuffer.length < 4) {
            return;
        }
        let length = totalBuffer.readInt16BE(2) + 4;
        //找到一份完整的报文,包含报头和正文,如果当前报文实际长度不满足报文长度,等待下一次数据传递,也就是接收下一次报文
        if (totalBuffer.length < length) {
            // console.warn('报文应长' + length + ',剩余报文长' + totalBuffer.length);
            return;
        }
        //如果当前报文长度满足报文应有长度,取出报文中的第一段,解压缩,并放置在完整报文数组中,并更新接收报文池中的报文
        let currentBuffer = totalBuffer.slice(0, length);
        readIndex += length;

        let newBuffer = ftdFactory.unCompressed(currentBuffer);
        //直接将解压缩之后的数据传递进去，用来解析

        //如果报文含拓展报头，则chain就不是第7个
        let extLength = newBuffer.readIntBE(1, 1);
        let chain;
        if (extLength === 0) {
            //换服务器后报文多出了字节，所以加了3个字节，相同修改再ftdFactory.js中也有
            chain = newBuffer.toString('ascii', 7, 8);
        } else {
            chain = newBuffer.toString('ascii', 4 + extLength, 5 + extLength);
        }
        var tid = newBuffer.slice(10, 14).toString('hex');
        setChainPackage(tid, newBuffer);
        //以上代码可能会去掉，待测试
        if (chain == 'L') {
            // 完成
            cleanChainPackage(tid);
        }

        if (receiverBuffer.length > readIndex) {
            analysisBuffer();
        } else if (receiverBuffer.length == readIndex) {
            let bufferLengthKB = receiverBuffer.length / 128;
            if (bufferLengthKB > 100) {
                receiverBuffer = new Buffer(0);
                readIndex = 0;
            }
        }
    }
};

class SendReceiver {
    constructor(port, host) {
        receivers = [];
        receiverBuffer = new Buffer(0);
        readIndex = 0;
        chainPackage = {};

        _conn = new net.createConnection({
            port: port,
            host: host
        });

        _conn.on('connect', () => {
            _connect_times = 0;
            console.log("服务器连接成功！");
            ipcRenderer.send('CONNECTED', true);
            //成功之后定时发送一个心跳
            var buffer = new Buffer([0x00, 0x02, 0x00, 0x00, 0x05, 0x00]);
            taskHeartBeat = setInterval(function() {
                _conn.write(buffer);
            }, 1000);
        });

        _conn.on('data', function(data) {
            if (data.length == 6) {
                console.log('接收到心跳包');
            } else {
                //暂时还是在同一个进程，阻塞式的读写文件，每次受到数据都做一次写的操作，然后做一次读的操作
                receiverBuffer = Buffer.concat([receiverBuffer, data]);
                analysisBuffer();
            }
        });


        _conn.on('timeout', (e) => {
            console.log('timeout');
        });

        _conn.on('error', (e) => {
            console.log(e);
        });

        _conn.on('close', function(e) {
            clearTimeout(taskHeartBeat);
            console.log('关闭了');
        });

    }

    sendPackage(data) {
    	console.log(data);
    }

    close() {

    }
}

export {SendReceiver};